import { Component } from 'react'
import { connect } from 'react-redux'
import Taro from '@tarojs/taro'
import { View, Text, Image, Input } from '@tarojs/components'
import { AtTextarea } from 'taro-ui'
import classnames from 'classnames'

import * as api from 'src/api'
import OrderGoods from 'src/components/OrderGoods'
import { EVENT_CHECK_STORE, EVENT_CHECK_ADDRESS } from 'src/constants'
import withPage from 'src/utils/withPage'

import './index.scss'

type IProps = {
  userInfo: { [key: string]: any }
}

type IState = {
  shippingType: 1 | 2
  storeInfo: { [key: string]: any }
  addressInfo: { [key: string]: any }
  orderInfo: { [key: string]: any }
  realName: string
  phone: string
  mark: string
}

interface Index {
  props: IProps
  state: IState
  cartId: string
  addressId: string
}

const connectRedux: Function = connect

@connectRedux(({ user }) => ({
  userInfo: user.userInfo,
}))
@withPage()
class Index extends Component {
  state: IState = {
    shippingType: 1,
    storeInfo: {},
    addressInfo: {},
    realName: this.props.userInfo.realName || '',
    phone: this.props.userInfo.phone || '',
    mark: '',
    orderInfo: {},
  }

  componentWillMount() {
    Taro.eventCenter.on(EVENT_CHECK_STORE, (storeInfo) => {
      this.setState({ storeInfo })
    })
    Taro.eventCenter.on(EVENT_CHECK_ADDRESS, (addressInfo) => {
      this.setState({ addressInfo })
    })
  }

  componentWillUnmount() {
    Taro.eventCenter.off(EVENT_CHECK_STORE)
    Taro.eventCenter.off(EVENT_CHECK_ADDRESS)
  }

  onLoad(options) {
    if (!options.cartId) {
      return Taro.showToast({ title: '请选择要购买的商品', icon: 'none' })
    }
    this.cartId = options.cartId
    this.addressId = options.addressId || 0
    this.getData()
  }

  getData = async () => {
    await Promise.allSettled([
      this.getOrderConfirm(),
      this.getStore(),
      this.getAddress(),
    ])
  }

  getOrderConfirm = async () => {
    const res = await api.orderConfirm({ cartIds: this.cartId })
    this.setState({ orderInfo: res || {} })
  }

  getStore = async () => {
    const res = await api.getStoreList()
    this.setState({ storeInfo: res[0] || {} })
  }

  getAddress = async () => {
    const res = await api.getAddressDefault()
    this.setState({ addressInfo: res || {} })
  }

  handleChangeShippingType = (shippingType) => {
    this.setState({ shippingType })
  }

  handleCheck = (url) => {
    Taro.navigateTo({
      url: `${url}?from_confirm=true`,
    })
  }

  handleChange = (key, e) => {
    this.setState({ [key]: e })
  }

  SubmitOrder = async () => {
    const {
      shippingType,
      storeInfo,
      addressInfo,
      realName,
      phone,
      mark,
      orderInfo,
    } = this.state
    if (!storeInfo.id) {
      return Taro.showToast({ title: '暂无门店,请选择其他方式', icon: 'none' })
    }
    if (shippingType === 1 && !addressInfo.id) {
      return Taro.showToast({ title: '请选择收货地址', icon: 'none' })
    }
    if (shippingType === 2) {
      if (realName === '' || phone === '') {
        return Taro.showToast({
          title: '请填写联系人或联系人电话',
          icon: 'none',
        })
      }
      if (!/^[\u4e00-\u9fa5\w]{2,16}$/.test(realName)) {
        return Taro.showToast({ title: '请填写您的真实姓名', icon: 'none' })
      }
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/.test(phone)) {
        return Taro.showToast({ title: '请填写正确的手机号', icon: 'none' })
      }
    }
    const data = {
      storeId: storeInfo.id || 0,
      shopId: storeInfo.id || 0,
      addressId: addressInfo.id,
      realName: realName,
      phone: phone,
      mark: mark,
      formId: '',
      couponId: 0,
      payType: 'offline',
      useIntegral: 'false',
      bargainId: 0,
      combinationId: 0,
      pinkId: 0,
      seckillId: 0,
      shippingType: shippingType,
      isNew: true,
      payChannel: 'routine',
    }
    Taro.showLoading({ title: '订单提交中' })
    try {
      const res = await api.orderCreate(orderInfo.orderKey, data)
      Taro.showToast({ title: '提交成功', icon: 'none' })
      Taro.navigateTo({
        url: `/pages/order_created/index?order_id=${res.orderNo}`,
      })
    } catch (error) {
      console.log(error)
      Taro.showToast({ title: error, icon: 'none' })
    }
  }

  render() {
    const {
      shippingType,
      storeInfo,
      addressInfo,
      realName,
      phone,
      mark,
      orderInfo,
    } = this.state
    return (
      <View className="order-confirm">
        <View className="store-address">
          <View className="nav at-row">
            <View
              className={classnames('item', {
                on: shippingType === 1,
                on2: shippingType !== 1,
              })}
              onClick={() => this.handleChangeShippingType(1)}
            ></View>
            <View
              className={classnames('item', {
                on: shippingType === 2,
                on2: shippingType !== 2,
              })}
              onClick={() => this.handleChangeShippingType(2)}
            ></View>
          </View>
          <View className="info at-row at-row__justify--between at-row__align--center">
            <View className="lable">付款门店</View>
            <View
              className="value at-row at-row__justify--between at-row__align--center"
              onClick={() => this.handleCheck('/pages/store_list/index')}
            >
              {storeInfo.id ? (
                <View className="address-wrap">
                  <View className="name">
                    {storeInfo.name}
                    <Text className="phone">{storeInfo.managerPhone}</Text>
                  </View>
                  <View className="line1">{storeInfo.address}</View>
                </View>
              ) : (
                <View className="no-address">暂无门店信息</View>
              )}
              <View className="at-icon at-icon-chevron-right"></View>
            </View>
          </View>
          {shippingType === 1 && (
            <View className="info at-row at-row__justify--between at-row__align--center">
              <View className="lable">收货地址</View>
              <View
                className="value at-row at-row__justify--between at-row__align--center"
                onClick={() => this.handleCheck('/pages/address_list/index')}
              >
                {addressInfo.id ? (
                  <View className="address-wrap">
                    <View className="name">
                      {addressInfo.realName}
                      <Text className="phone">{addressInfo.phone}</Text>
                    </View>
                    <View className="line1">
                      <text className="default">[默认]</text>
                      {addressInfo.province}
                      {addressInfo.city}
                      {addressInfo.district}
                      {addressInfo.detail}
                    </View>
                  </View>
                ) : (
                  <View className="no-address">设置收货地址</View>
                )}
                <View className="at-icon at-icon-chevron-right"></View>
              </View>
            </View>
          )}
          {shippingType === 2 && (
            <>
              <View className="info at-row at-row__justify--between at-row__align--center">
                <View className="lable">联系人</View>
                <View className="at-col">
                  <Input
                    type="text"
                    value={realName}
                    onInput={(e) =>
                      this.handleChange('realName', e.detail.value)
                    }
                    placeholder="请填写您的联系姓名"
                  />
                </View>
              </View>
              <View className="info at-row at-row__justify--between at-row__align--center">
                <View className="lable">联系电话</View>
                <View className="at-col">
                  <Input
                    type="text"
                    value={phone}
                    onInput={(e) => this.handleChange('phone', e.detail.value)}
                    placeholder="请填写您的联系电话"
                  />
                </View>
              </View>
            </>
          )}
          <View className="line">
            <Image src="/static/images/line.jpg"></Image>
          </View>
        </View>
        <OrderGoods cartInfo={orderInfo.cartInfo} />
        <View className="wrapper">
          <View className="item at-row at-row__justify--between">
            <View>优惠</View>
            <View className="money">
              -￥{orderInfo.priceGroup?.userMarkPrice}
            </View>
          </View>
          <View className="item at-row at-row__justify--between">
            <View>商品总价</View>
            <View className="money">￥{orderInfo.priceGroup?.totalPrice}</View>
          </View>
          <View className="item">
            <View>备注信息</View>
            <AtTextarea
              className="textarea"
              value={mark}
              onChange={(e) => this.handleChange('mark', e)}
              maxLength={150}
              placeholder="请添加备注"
            />
          </View>
        </View>
        <View style={{ height: 60 }}></View>
        <View className="footer at-row at-row__justify--between at-row__align--center">
          <View>
            合计:
            <text className="price-color">
              ￥{orderInfo.priceGroup?.totalPrice}
            </text>
          </View>
          <View className="settlement" onClick={this.SubmitOrder}>
            提交订单
          </View>
        </View>
      </View>
    )
  }
}

export default Index
